package com.xrui.hbase.cdf;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

/**
 * Created by U0121467 on 8/30/2017.
 */
public class ByteConverter {

    public static byte[] getBytesFromFile(String fileName) {
        try {
            byte[] rawBytes = Files.readAllBytes(Paths.get(fileName));
            return getRealBytes(rawBytes);
        }
        catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] getRealBytes(byte[] rawBytes) {
        int rawLen = rawBytes.length;
        byte[] cvtBytes = new byte[rawLen];
        int cvtLen = 0;
        for(int i = 0; i < rawLen;) {
            if(i > rawLen - 4) {
                cvtBytes[cvtLen] = rawBytes[i];
                i += 1;
            }
            else if(92 == rawBytes[i] && 120 == rawBytes[i + 1]) {
                int i1 = ascii2int(rawBytes[i + 2]);
                int i2 = ascii2int(rawBytes[i + 3]);
                cvtBytes[cvtLen] = (byte)(i1 * 16 + i2);
                i += 4;
            }
            else {
                cvtBytes[cvtLen] = rawBytes[i];
                i += 1;
            }
            cvtLen += 1;
        }
        byte[] finalBytes = Arrays.copyOfRange(cvtBytes, 0, cvtLen);
        return finalBytes;
    }

    private static int ascii2int(byte i) {
        if(48 <= i && i <= 57) return (i - 48);
        else if(65 <= i && i <= 70) return (i - 55);
        else return 0;
    }

}
